package com.shiro.test.exception;

import com.auth0.jwt.exceptions.TokenExpiredException;
import com.shiro.test.response.Response;
import org.apache.shiro.ShiroException;
import org.apache.shiro.authc.AccountException;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.CredentialsException;
import org.apache.shiro.authc.pam.ShortCircuitIterationException;
import org.apache.shiro.authc.pam.UnsupportedTokenException;
import org.apache.shiro.authz.AuthorizationException;
import org.apache.shiro.authz.UnauthenticatedException;
import org.apache.shiro.authz.UnauthorizedException;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.servlet.http.HttpServletRequest;

@RestControllerAdvice
public class ExceptionAdvice {


    //认证异常
    @ExceptionHandler(UnauthenticatedException.class)
    public Response handle(UnauthenticatedException e) {
        return new Response(401, "认证异常", e.getMessage(), null);
    }

    //授权异常
    @ExceptionHandler(UnauthorizedException.class)
    public Response handle(UnauthorizedException e) {
        return new Response(402, "授权异常", e.getMessage(), null);
    }

    //账号异常
    @ExceptionHandler(AccountException.class)
    public Response handle(AccountException e) {
        return new Response(403, "AccountException", e.getMessage(), null);
    }

    //证书异常
    @ExceptionHandler(CredentialsException.class)
    public Response handle(CredentialsException e) {
        return new Response(404, "CredentialsException", e.getMessage(),  null);
    }


    @ExceptionHandler(ShortCircuitIterationException.class)
    public Response handle(ShortCircuitIterationException e) {
        return new Response(405, "ShortCircuitIterationException", e.getMessage(), null);
    }

    //不支持的token
    @ExceptionHandler(UnsupportedTokenException.class)
    public Response handle(UnsupportedTokenException e) {
        return new Response(406, "UnsupportedTokenException", e.getMessage(), null);
    }


    // 捕捉其他所有异常
    @ExceptionHandler(Exception.class)
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public Response globalException(HttpServletRequest request, Throwable ex) {
        return new Response(getStatus(request).value(),"exception", ex.getMessage(), null);
    }


    private HttpStatus getStatus(HttpServletRequest request) {
        Integer statusCode = (Integer) request.getAttribute("javax.servlet.error.status_code");
        if (statusCode == null) {
            return HttpStatus.INTERNAL_SERVER_ERROR;
        }
        return HttpStatus.valueOf(statusCode);
    }
}

